from ...pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...service.buss_pub.bill_manage import BillManageService, OperationType, Status, TypeId
from ...service.common import get_info, operation_result, find_data, get_current_user_id
from ...pao_python.pao.data import process_db
from ...service.mongo_bill_service import MongoBillFilter
from enum import Enum
import copy


class NursingTable(Enum):
    project = 'PT_Nursing_Project'
    template = 'PT_Nursing_Template'
    recode = 'PT_Nursing_Recode'


class NursingManage(MongoService):

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        self.db_user = db_user
        self.db_pwd = db_pwd
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_server = BillManageService(
            self.db_addr, self.db_port, self.db_name, self.db_user, self.db_pwd, self.inital_password, self.session)

    def update_nursing_project(self, condition, table_name, Type):
        ''' 新增/编辑护理项目/模板
            Args:
                condition   项目/模板数据
                table_name  护理项目/模板数据库表名称
        '''
        flag = OperationType.update.value
        if not 'id' in condition.keys():
            flag = OperationType.add.value
            condition = get_info(condition, self.session)
        bill_id = self.bill_manage_server.add_bill(
            flag, Type, condition, table_name)
        return operation_result(bill_id)

    # def get_nursing_template_list(self, org_list, condition, page, count):
    #     key = ['id', 'name']
    #     _filter = MongoBillFilter()
    #     values = self.get_value(condition, key)
    #     _filter.match_bill((C('id') == values['id']) & (C('name').like(values['name'])) & (C('organization_id').inner(org_list)))\
    #         .lookup_bill(NursingTable.project.value, 'dataSource.project_id', 'id', 'project')\
    #         .project({'_id': 0, 'project._id': 0})
    #     res = self.page_query(
    #         _filter, NursingTable.template.value, page, count)
    #     return res

    def get_nursing_project_list(self, org_list, table_name, condition, page, count):
        '''获取护理项目列表'''
        key = ['id', 'name']
        _filter = MongoBillFilter()
        values = self.get_value(condition, key)
        _filter.match_bill((C('id') == values['id']) & (C('name').like(values['name'])) & (C('organization_id').inner(org_list))) \
               .project({'_id': 0})
        res = self.page_query(_filter, table_name, page, count)
        return res

    def delete_nursing_project(self, ids, table_name, Type):
        '''删除护理项目/模板'''
        res = 'Fail'

        def process_func(db):
            nonlocal res
            for id in ids:
                data = find_data(db, table_name, {
                                 'id': id, 'bill_status': Status.bill_valid.value})
                if len(data) > 0:
                    self.bill_manage_server.add_bill(OperationType.delete.value,
                                                     Type, data[0], table_name)
            res = 'Success'
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return res

    def get_nursing_template_list(self, org_list, condition, page, count):
        key = ['id', 'name']
        _filter = MongoBillFilter()
        values = self.get_value(condition, key)
        _filter.match_bill((C('id') == values['id']) & (C('name').like(values['name'])) & (C('organization_id').inner(org_list))) \
               .lookup_bill(NursingTable.project.value, 'dataSource.project_id', 'id', 'project')\
               .project({'_id': 0, 'project._id': 0})
        res = self.page_query(
            _filter, NursingTable.template.value, page, count)
        return res

    def get_nursing_recode_list(self, org_id, condition, page, count):
        '''获取护理记录'''
        key = ['id', 'name', 'date', 'worker_name']
        values = self.get_value(condition, key)
        _filter = MongoBillFilter()
        _filter.inner_join_bill('PT_User', 'obj.elder', 'id', 'user') \
            .inner_join_bill('PT_User', 'servicer_id', 'id', 'worker')\
               .match_bill(
                   (C('id') == values['id'])
                   & (C('user.name').like(values['name']))
                   & (C('worker.name').like(values['worker_name']))
                   & (C('organization_id').inner(org_id))
        ) \
            .project({'_id': 0, 'user._id': 0, 'worker._id': 0})
        print("<<<<<<<<<<<<<<", _filter.filter_objects)
        res = self.page_query(_filter, NursingTable.recode.value, page, count)
        return res

    def get_nursing_recode_list_look(self, condition, page, count):
        '''获取护理记录'''
        key = ['id', 'name', 'date', 'worker_name']
        values = self.get_value(condition, key)
        _filter = MongoBillFilter()
        _filter.inner_join_bill('PT_User', 'obj.elder', 'id', 'user') \
            .inner_join_bill('PT_User', 'servicer_id', 'id', 'worker')\
               .match_bill(
                   (C('id') == values['id'])
                   & (C('user.name').like(values['name']))
                   & (C('worker.name').like(values['worker_name']))
        ) \
            .project({'_id': 0, 'user._id': 0, 'worker._id': 0})
        print("<<<<<<<<<<<<<<", _filter.filter_objects)
        res = self.page_query(_filter, NursingTable.recode.value, page, count)
        return res

    def update_nursing_recode(self, condition):
        '''新增/编辑护理记录'''
        condition['servicer_id'] = get_current_user_id(self.session)
        param = [condition]
        table_name = [NursingTable.recode.value]
        flag = OperationType.update.value
        if 'id' not in condition.keys():  # 新建
            param.clear()
            table_name.clear()
            new_coditon = copy.deepcopy(condition)
            new_coditon['obj']['project_list'].clear()
            new_coditon = get_info(new_coditon, self.session)
            flag = OperationType.add.value
            for x in condition['obj']['project_list']:
                recode = copy.deepcopy(new_coditon)
                recode['obj']['project_list'].append(x)
                param.append(recode)
                table_name.append(NursingTable.recode.value)
        bill_id = self.bill_manage_server.add_bill(
            flag, TypeId.nursingRecode.value, param, table_name)
        return operation_result(bill_id)
